import { set, max } from "lodash-es"
import nodeIconUrl from "./svg/tabler--point-filled.svg?url"
import {t} from "./i18n/index"

const PORT_ATTRS: any = {
    circle: {
        magnet: true,
        stroke: '#8f8f8f',
        r: 5,
    },
}
export const DEFAULT_PORTS_GROUPS: any = {
    left: { position: 'left', attrs: PORT_ATTRS },
    top: { position: "top", attrs: PORT_ATTRS },
    bottom: { position: 'bottom', attrs: PORT_ATTRS },
    right: { position: 'right', attrs: PORT_ATTRS },
    "arrow-left": {
        position: { name: 'left' },
        markup: [
            {
                tagName: 'path',
                selector: 'path',
            },
        ],
        attrs: {
            path: {
                d: 'M -4 4 L -4 -4 L 0 0 Z',
                magnet: true,
                stroke: '#31d0c6',
                fill: '#fff',
                strokeWidth: 2,
            },
        },
    }
}

export const DICT_EDGES: any[] = [
    { router: "normal", connector: "normal", name: "normal", desc: t('util-edges-normal'), icon: "i-teenyicons:line-outline" },
    { router: "manhattan", connector: "rounded", name: "manhattan", desc: t('util-edges-manhattan'), icon: 'i-teenyicons:elbow-connector-outline' },
    { router: "metro", connector: "normal", name: "metro", desc: t('util-edges-metro'), icon: 'i-lets-icons:line-alt' },
    { router: "normal", connector: "smooth", name: "smooth", desc: t('util-edges-smooth'), icon: 'i-teenyicons:curved-connector-outline' },
]

// sdagre:'i-carbon:skill-level-advanced',ellipse:'i-mdi:ellipse-outline'
export const DICT_LAYOUT = [
    {name:"self",icon:"i-fluent:grid-20-regular",desc:t('util-layout-self')},
    {name:"grid",icon:"i-fluent:grid-dots-24-filled",desc:t('util-layout-grid')},
    {name:"circular",icon:"i-mdi:selection-ellipse",desc:t('util-layout-circular')},
    {name:"dagre",icon:"i-carbon:skill-level-advanced",desc:t('util-layout-dagre')},
    {name:"ellipse",icon:"i-mdi:selection-ellipse",desc:t('util-layout-ellipse')},

]

// 默认节点
export const DefaultNodeMD = {
    width: 160,
    height: 40,
    zIndex:100,
    attrs: {
        body: {
            stroke: '#409EFF',
            strokeWidth: 2,
            fill: 'rgba(255,255,255,1)',
            refWidth: 1,
            refHeight: 1,
            rx: 8,
            ry: 8,
        },
        iconbox: {
            xAlign: "left",
            // yAlign: "middle",
            fontSize: 24,
            refX: "10",
            refY: "50%",
            refY2: -12,
        },
        icon: {
            width: "1em",
            height: "1em",
            class: "",
        },
        image: {
            xlinkHref: nodeIconUrl,
            width: "20",
            height: "20",
            xAlign: "left",
            yAlign: "middle",
            refX: "10",
            refY: "50%",
            stroke: '#409EFF',
            strokeWidth: 2,
        },
        label: {
            refX: "40",
            refY: "50%",
            fontSize: 18,
            xAlign: "left",
            yAlign: "middle",
            fill: "#666",
            text: "",
            textWrap: {
                width: 110,
                height: "20",
                ellipsis: true,
            }
        },
    },
    markup: [
        { tagName: 'rect', selector: 'body' },
        {
            tagName: "foreignObject",
            selector: "iconbox",
            children: [
                {
                    ns: "http://www.w3.org/1999/xhtml",
                    tagName: "div",
                    selector: "icon",
                }
            ]
        },
        { tagName: "image", selector: "image" },
        { tagName: 'text', selector: 'label' },
    ],
    ports: {
        groups: DEFAULT_PORTS_GROUPS,
        items: [{ id: "in", group: "left" }, { id: "out", group: "right" }]
    },
    propHooks(metadata: any) {
        const { icon, label, imgurl } = metadata;
        if (icon && typeof icon == 'string') {
            set(metadata, 'attrs.icon.class', icon)
            set(metadata, 'attrs.image.display', 'none')
        }
        else if (imgurl) {
            set(metadata, 'attrs.image.xlinkHref', imgurl)
            set(metadata, 'attrs.iconbox.display', 'none')
        }
        if (label) { set(metadata, 'attrs.label.text', label) }
        return metadata;
    }
}
// 默认边
export const DefaultEdgeMD = {
    inherit: 'edge',
    zIndex:10,
    attrs: {
        line: {
            stroke: '#409EFF',
            strokeDasharray: 5,
            targetMarker: 'classic',
            style: {
                animation: 'ant-line 30s infinite linear',
            },
        },
    },
}


// 计算可用最大 index 
export const maxIndex = (parent: HTMLElement) => {
    return 1 + (max([...parent.querySelectorAll('*')].map(e => +window.getComputedStyle(e).zIndex || 0).filter(n => n > 0)) || 0);
}


// 存缓存
const PREFIX_GRAPH = 'X6-UI-'
//
export const saveToStore = (name: string, value: any) => {
    const data = { value, type: typeof value, time: new Date().getTime() };
    localStorage.setItem(`${PREFIX_GRAPH}${name}`, JSON.stringify(data))
}

export const getFromStore = (name: string, dv?: any) => {
    const t = localStorage.getItem(`${PREFIX_GRAPH}${name}`);
    if (t) {
        const data = JSON.parse(t);
        return data.value;
    }
    return dv || undefined;
}

// 创建 input 元素 触发 导入功能 并注册成功事件以解析文件
export const importBtn = (callback: (args: any) => void) => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json'
    input.setAttribute('style', 'opacity:0;width:0;height:0;position:absolute;z-index:-1;')
    // document.body.appendChild(input)
    input.addEventListener('change', (evt) => {
        // @ts-ignore
        const file = evt?.target?.files[0];
        if (file) {
            var reader = new FileReader();
            reader.onload = function (e) {
                // @ts-ignore
                callback(e.target.result);  
            };
            reader.readAsText(file);
        }
        //
        input.remove();
    })
    input.click();
}

// 创建 A 标签触发下载一个文本
export const exportBtn = (s:string,name = 'graph.json') => {
    const blob = new Blob([s]);
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = name;
    a.click();
}